import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/group_snapshot.dart';
import 'package:vista/shared/models/moment_shot.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/circle_gallery.dart';
import 'package:vista/shared/services/post_studio.dart';

/// 社区视图模型
/// 管理社区页面的数据和状态
class CommunityViewModel extends BaseViewModel {
  final AuthFocus _authFocus;
  final CircleGallery _circleGallery;
  final PostStudio _postStudio;

  CommunityViewModel(this._authFocus, this._circleGallery, this._postStudio);

  List<GroupSnapshot> _circles = [];
  List<GroupSnapshot> get circles => _circles;

  List<MomentShot> _dailyLifePosts = [];
  List<MomentShot> get dailyLifePosts => _dailyLifePosts;

  List<MomentShot> _photographyPosts = [];
  List<MomentShot> get photographyPosts => _photographyPosts;

  Map<String, UserFrame> _userMap = {};
  UserFrame? getUserById(String userId) => _userMap[userId];

  Map<String, List<String>> _circleMembers = {};
  List<String> getCircleMembers(String circleId) =>
      _circleMembers[circleId] ?? [];

  UserFrame? _currentUser;
  UserFrame? get currentUser => _currentUser;

  Map<String, bool> _likedMap = {};
  Map<String, int> _likeCountMap = {};

  bool isLiked(String postId) => _likedMap[postId] ?? false;
  int getLikeCount(String postId) => _likeCountMap[postId] ?? 0;

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      _currentUser = await _authFocus.getCurrentUser();
      await _loadCircles();
      await _loadDailyLifePosts();
      await _loadPhotographyPosts();
      await _loadUsers();
      await _loadCircleMembers();
      await _loadLikeStatuses();
    } finally {
      setBusy(false);
    }
  }

  /// 加载圈子列表
  Future<void> _loadCircles() async {
    _circles = await _circleGallery.getAllGroups();
    notifyListeners();
  }

  /// 加载日常生活动态
  Future<void> _loadDailyLifePosts() async {
    _dailyLifePosts = await _postStudio.getPostsByCategory(
      PostCategory.dailyLife,
    );
    notifyListeners();
  }

  /// 加载摄影动态
  Future<void> _loadPhotographyPosts() async {
    _photographyPosts = await _postStudio.getPostsByCategory(
      PostCategory.photography,
    );
    notifyListeners();
  }

  /// 加载用户信息
  Future<void> _loadUsers() async {
    final users = await _authFocus.getUsers();
    _userMap = {for (var user in users) user.id: user};
    notifyListeners();
  }

  /// 加载圈子成员
  Future<void> _loadCircleMembers() async {
    for (final circle in _circles) {
      final members = await _circleGallery.getGroupMembers(circle.id);
      _circleMembers[circle.id] = members;
    }
    notifyListeners();
  }

  /// 加载点赞状态
  Future<void> _loadLikeStatuses() async {
    final allPosts = [..._dailyLifePosts, ..._photographyPosts];
    for (final post in allPosts) {
      // 无论是否登录，都加载点赞数量
      _likeCountMap[post.id] = await _postStudio.getLikeCount(post.id);

      // 只有登录用户才加载点赞状态
      if (_currentUser != null) {
        _likedMap[post.id] = await _postStudio.isLiked(
          post.id,
          _currentUser!.id,
        );
      }
    }
    notifyListeners();
  }

  /// 切换点赞状态
  Future<void> toggleLike(String postId) async {
    if (_currentUser == null) return;

    final isLiked = _likedMap[postId] ?? false;
    if (isLiked) {
      await _postStudio.unlikePost(postId, _currentUser!.id);
    } else {
      await _postStudio.likePost(postId, _currentUser!.id);
    }

    _likedMap[postId] = !isLiked;
    _likeCountMap[postId] = await _postStudio.getLikeCount(postId);
    notifyListeners();
  }

  /// 删除动态
  Future<void> deletePost(String postId) async {
    await _postStudio.deletePost(postId);
    _dailyLifePosts.removeWhere((post) => post.id == postId);
    _photographyPosts.removeWhere((post) => post.id == postId);
    _likedMap.remove(postId);
    _likeCountMap.remove(postId);
    notifyListeners();
  }

  /// 刷新数据
  Future<void> refresh() async {
    await initialize();
  }

  /// 检查用户是否已加入圈子
  Future<bool> isMember(String circleId) async {
    if (_currentUser == null) return false;
    return await _circleGallery.isMember(circleId, _currentUser!.id);
  }

  /// 加入圈子
  Future<void> joinCircle(String circleId) async {
    if (_currentUser == null) return;

    await _circleGallery.joinGroup(circleId, _currentUser!.id);
    // 刷新圈子成员列表
    await _loadCircleMembers();
  }

  /// 刷新当前用户
  Future<void> refreshCurrentUser() async {
    _currentUser = await _authFocus.getCurrentUser();
    notifyListeners();
  }
}
